<template>
  <el-dialog
    title="卡券秘钥"
    :close-on-click-modal="false"
    @close="closeHandle"
    :visible.sync="visible"
    append-to-body>
    <el-form :inline="true" :model="searchForm" @keyup.enter.native="pageIndex = 1;getDataList()">
      <el-form-item>
        <el-input v-model="searchForm.cardSn" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.status" clearable filterable placeholder="请选择" class="width185">
          <el-option v-for="attribute in [{id:0,name:'可用'}, {id:1,name:'已领取'}, {id:2,name:'已使用'}]"
                     :value="attribute.id"
                     :label="attribute.name"
                     :key="attribute.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="pageIndex = 1; getDataList()">查询</el-button>
        <el-button v-if="isAuth('mall:cardsn:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="isAuth('mall:cardsn:save')" type="primary" @click="batchHandle()">批量导入</el-button>
        <el-button v-if="isAuth('mall:cardsn:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
      <el-form-item>
<!--        <el-input-number v-model="number">批量生成数量</el-input-number>-->
<!--        <el-button v-if="isAuth('mall:cardsn:save')" type="primary" @click="batchAddHandle()">批量生成自有卡券</el-button>-->
        <el-button v-if="isAuth('mall:cardsn:save')" type="primary" @click="downHandle()">导出数据</el-button>
<!--        <el-button v-if="isAuth('mall:cardsn:save')" type="primary" @click="batchAddHandle(1)">批量生成外部系统卡券</el-button>-->
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="cardSn"
        header-align="center"
        align="center"
        label="卡券编码">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" size="small" type="danger">可用</el-tag>
          <el-tag v-else-if="scope.row.status === 1" size="small" type="success">已领取</el-tag>
          <el-tag v-else-if="scope.row.status === 2" size="small" type="success">已使用</el-tag>
          <el-tag v-else-if="scope.row.status === 3" size="small" type="warning">冻结</el-tag>
          <el-tag v-else-if="scope.row.status === 4" size="small" type="danger">过期</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('mall:cardsn:info')" type="text" size="small" @click="showDetails(scope.row.id)">查看</el-button>
          <el-button v-if="isAuth('mall:cardsn:update')" type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button v-if="isAuth('mall:cardsn:delete')" type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <sn-upload v-if="batchVisible" ref="snUpload" @refreshDataList="getDataList"></sn-upload>
  </el-dialog>
</template>

<script>
import AddOrUpdate from './cardsn-add-or-update'
import SnUpload from './card-sn-upload'

export default {
  data() {
    return {
      isClick: true,
      searchForm: {
        cardSn: ''
      },
      cardId: '',
      number: 0,
      dataList: [],
      pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListSelections: [],
        addOrUpdateVisible: false,
        batchVisible: false,
        visible: false
      }
    },
    components: {
      AddOrUpdate, SnUpload
    },
    activated () {
    },
    methods: {
      getDataList () {
        this.init(this.cardId)
      },
      // 获取数据列表
      init (cardId) {
        this.cardId = cardId
        this.visible = true
        let params = {
          'cardSn': this.searchForm.cardSn,
          'page': this.pageIndex,
          'limit': this.pageSize,
          'goodsId': cardId
        }
        if(this.searchForm.status!==''){
          params.status = this.searchForm.status
        }
        this.$http({
          url: '/mall/cardsn/list',
          method: 'get',
          params: params
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.records
            this.totalPage = data.page.total
          } else {
            this.dataList = []
            this.totalPage = 0
          }
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 查看详情
      showDetails (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id, true)
        })
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id, false, this.cardId)
        })
      },
      batchHandle (id) {
        this.batchVisible = true
        this.$nextTick(() => {
          this.$refs.snUpload.init(this.cardId)
        })
      },
      downHandle (id) {
        let ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })

        this.$http({
          url: '/mall/cardsn/downLoad',
          method: 'POST',
          data: {
            'ids': ids,
            'status' : this.searchForm.status,
            'goodsId': this.cardId
          },
          responseType: 'blob'
          // responseType: 'blob'
        }).then(res=>{
          // console.log(res.headers)
          const filesNameCode = res.headers["content-disposition"]
            .split(";")[1]
            .split("=")[1]
          const fileName = decodeURI(filesNameCode);
          const a = document.createElement("a");
          const result = res.data;
          const blob = new Blob([result], {
            type: ".xlsx", //vnd.openxmlformats-officedocument.spreadsheetml.sheet
          });
          // console.log(blob)
          a.style.display = "none";
          const url = window.URL || window.webkitURL || window.moxURL;
          a.href = url.createObjectURL(blob);
          a.download = fileName;
          a.click();
          window.URL.revokeObjectURL(url);

        })

        // then(({}) => {
        //   // if (data && data.code === 0 && data.list.length > 0) {
        //   //   const { export_json_to_excel } = require('../../../excel/Export2Excel')
        //   //   const tHeader = ['卡券秘钥', '卡券类型']// 对应表格输出的title
        //   //   const filterVal = ['cardSn', 'type'] // 对应表格输出的数据
        //   //   // var i = 0
        //   //   // for (; i < data.page.total; i++) {
        //   //   //   if (data.page.records[i].type === 1) {
        //   //   //     data.page.records[i].cardSn = 'https://platform.hndyjr.com/dist/#/couponKey?a=' + data.page.records[i].cardId + '&b=' + data.page.records[i].cardSn + '&c=' + data.page.records[i].c
        //   //   //     data.page.records[i].type = 2
        //   //   //   }
        //   //   // }
        //   //   const exceldata = this.formatJson(filterVal, data.list)
        //   //   export_json_to_excel([tHeader], [exceldata], '订单数据')// 对应下载文件的名字
        //   // } else {
        //   //   this.$message({
        //   //     message: '未查找到数据',
        //   //     type: 'success',
        //   //     duration: 1500
        //   //   })
        //   // }
        // })
      },
      formatJson (filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      batchAddHandle (mark) {
        if (!this.number) {
          this.$message({
            message: '请填写数量',
            type: 'error',
            duration: 1500
          })
        }
        let data = {
          'cardId': this.cardId,
          'mark': mark,
          'number': this.number
        }
        this.$http({
          url: `/mall/cardsn/batchSave`,
          method: 'post',
          data: data
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
            this.init(this.cardId)
          }
        })
      },
      // 弹窗关闭时
      closeHandle () {
        this.dataList = []
        this.visible = false
      },
      // 删除
      deleteHandle (id) {
        let ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[删除]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: '/mall/cardsn/delete',
            method: 'post',
            data: ids
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500
              })
              this.getDataList()
            }
          })
        }).catch(() => {
        })
      }
    }
  }
</script>
